package xml;

import java.awt.Dimension;
import java.awt.Point;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

/**
 * Common XML functions for parsing into and out of XML format
 * 
 * @author Trevor Bastian
 * @date March 31, 2010
 * @version 4.0
 * 
 * @since Version 4.0
 *
 */
public class XMLcommon {
	public static Element pointToXML (Document doc, Point p) {
		Element point, element;
		Text text;
		
		point = doc.createElement(Point.class.getName());
		
		element = doc.createElement("X");
		text = doc.createTextNode("" + p.x);
		element.appendChild(text);
		point.appendChild(element);
		
		element = doc.createElement("Y");
		text = doc.createTextNode("" + p.y);
		element.appendChild(text);
		point.appendChild(element);

		return point;
	}
	
	public static Point parseXMLPoint (Element e) {
		String x, y;
		
		x = getTextValue (e, "X");
		y = getTextValue(e, "Y");
		
		return new Point (Integer.parseInt(x), Integer.parseInt(y));
	}

	public static Element dimensionToXML (Document doc, Dimension d) {
		Element dim, element;
		Text text;
		
		dim = doc.createElement(Dimension.class.getName());
		
		element = doc.createElement("Height");
		text = doc.createTextNode("" + d.height);
		element.appendChild(text);
		dim.appendChild(element);
		
		element = doc.createElement("Width");
		text = doc.createTextNode("" + d.width);
		element.appendChild(text);
		dim.appendChild(element);

		return dim;
	}
	
	public static Dimension parseXMLDimension (Element e) {
		String height, width;
		
		height = getTextValue (e, "Height");
		width = getTextValue(e, "Width");
		
		return new Dimension (Integer.parseInt(height), Integer.parseInt(width));
	}
	
	/**
	 * I take a xml element and the tag name, look for the tag and get
	 * the text content 
	 * @param ele
	 * @param tagName
	 * @return
	 */
	public static String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}
}
